package com.qipay.sp.excutor.dafu;

import com.alibaba.fastjson.JSONObject;
import com.qipay.baas.model.Order;
import com.qipay.order.config.OrderStateEnum;
import com.qipay.order.service.OrderService;
import com.qipay.scalar.type.ApiStatusEnum;
import com.qipay.sp.excutor.AbstractExcutor;
import com.qipay.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Component
public class DafuAliWapExcutor extends AbstractExcutor {

    private final static String API_URL="api_url";
    @Autowired
    OrderService orderService;

    @Override
    protected Map<String, Object> getApiParams(Order order, Map<String, Object> spconfig, Map<String, Object> extendOrderParams) {
        Map<String, Object> apiParams = new HashMap<>();
        apiParams.put("order_sn",order.getTradeNo());
        apiParams.put("money",new BigDecimal(order.getAmount()).divide(new BigDecimal("100")).floatValue());
        apiParams.put("format","json");
        apiParams.put("time",String.valueOf(System.currentTimeMillis() / 1000));
        apiParams.put("goods_desc",order.getBody());
        apiParams.put("client_ip",order.getRemark());

        return apiParams;
    }

    @Override
    protected Map<String, Object> run(Map<String, Object> spconfig, Map<String, Object> params) throws Exception {
        Object apiUrl = getVal(spconfig, API_URL);
        Object mch_id = getVal(spconfig, "mch_id");//商户uid
        Object notifyUrl= getVal(spconfig, "notify_url");
        Object key= getVal(spconfig, "key");

        params.put("mch_id",mch_id);
        params.put("notify_url",notifyUrl);
        String sign = MD5Util.getSign(params,key.toString()).toLowerCase();
        params.put("sign",sign);
        params.put("key",key);
        String result = http(apiUrl.toString(),params);
        Order order = orderService.getByTradeNo(params.get("order_sn").toString());
        Map<String, Object> resultMap = new HashMap<>();
        JSONObject jsonObject = JSONObject.parseObject(result);

        if("1".equals(jsonObject.getString("code"))){
            JSONObject jsonData = jsonObject.getJSONObject("data");
            String url= jsonData.getString("jump_url");
            resultMap.put("status", ApiStatusEnum.OK.getCode());
            resultMap.put("pay_info",url);
            order.setState(OrderStateEnum.WAITING.getType());
        }else {
            resultMap.put("status", "1");
            resultMap.put("message", jsonObject.getString("msg"));
            order.setState(OrderStateEnum.REQERROR.getType());
        }
        orderService.update(order);
        return resultMap;
    }

}
